package JDBC;

import java.sql.*;

/**
 * 测试事务的基本概念和用法
 */
public class demo6 {
    public static void main(String[] args) {
        Connection conn= null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            //加载类驱动
            Class.forName("com.mysql.jdbc.Driver");
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/zz?characterEncoding=UTF-8","root","123456");
            conn.setAutoCommit(false);//JDBC默认true提交事务

            ps1 = conn.prepareStatement("INSERT INTO user (userName,age) VALUES (?,?)");
            ps1.setObject(1,"赵六");
            ps1.setObject(2,100);
            ps1.execute();
            System.out.println("插入一个用户");
            Thread.sleep(3000);

            ps1 = conn.prepareStatement("INSERT INTO user (userName,age) VALUES (?,?,?)");//故意写三个？让操作失败，整个事务失败回滚
            ps1.setObject(1,"理四");
            ps1.setObject(2,100);
            ps1.execute();
            System.out.println("插入一个用户");

            conn.commit();


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            try {
                conn.rollback();//回滚
            } catch (SQLException e1) {
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if(ps1!=null){
                    ps1.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(conn!=null){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
